/**
 * 
 */
package com.gs.practice.thread.javathreads.ch02.ex7;

import java.util.Random;

import com.gs.practice.thread.javathreads.ch02.CharacterEventHandler;
import com.gs.practice.thread.javathreads.ch02.CharacterListener;
import com.gs.practice.thread.javathreads.ch02.CharacterSource;

/**
 * @author Sabuj Das | sabuj.das@gmail.com
 *
 */
public class RandomCharacterGenerator implements Runnable, CharacterSource {

	public final static char[] CHARS;
	public final static String CHAR_ARRAY = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	
	static{
		CHARS = CHAR_ARRAY.toCharArray();
	}
	
	private Random random;
	private CharacterEventHandler handler;
	
	/**
	 * 
	 */
	public RandomCharacterGenerator() {
		random = new Random();
		handler = new CharacterEventHandler();
	}
	
	public int getPauseTime(){
		return (int) (Math.max(1000, 10000 * random.nextDouble()));
	}

	@Override
	public void addCharacterListener(CharacterListener listener) {
		handler.addCharacterListener(listener);
	}

	@Override
	public void removeCharacterListener(CharacterListener listener) {
		handler.removeCharacterListener(listener);
	}

	@Override
	public void nextCharacter() {
		int cc =  
				(int) CHARS[random.nextInt(CHARS.length)];
		handler.fireNewCharacter(this, cc);
	}
	
	@Override
	public void run() {
		while(true){
			nextCharacter();
			try {
				Thread.sleep(getPauseTime());
			} catch (InterruptedException e) {
				return;
			}
		}
	}
}
